
class WasmCalculator {
    constructor() {
        this.module = null;
        this.history = JSON.parse(localStorage.getItem('calcHistory')) || [];
        this.init();
    }

    async init() {
        try {
            // 显示加载状态
            document.getElementById('wasmStatus').innerHTML = 
                '<span class="loading-spinner"></span>正在加载 WebAssembly 模块...';
            
            // 编译和加载 WebAssembly 模块
            this.module = await this.compileWasm();
            
            document.getElementById('wasmStatus').innerHTML = 
                '<i class="fas fa-check-circle text-green-500 mr-2"></i>WebAssembly 模块已成功加载！';
            
            console.log('WebAssembly 模块加载成功:', this.module);
            this.updateHistoryDisplay();
            
        } catch (error) {
            console.error('WebAssembly 加载失败:', error);
            document.getElementById('wasmStatus').innerHTML = 
                '<i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>WebAssembly 模块加载失败';
        }
    }

    async compileWasm() {
        // 这里应该加载预编译的 .wasm 文件
        // 为了演示，我们使用模拟的 WebAssembly 函数
        return {
            _add: (a, b) => a + b,
            _subtract: (a, b) => a - b,
            _multiply: (a, b) => a * b,
            _divide: (a, b) => b !== 0 ? a / b : 0,
            _power: (a, b) => Math.pow(a, b),
            _squareRoot: (a) => a >= 0 ? Math.sqrt(a) : -1
        };
    }

    performOperation(operation) {
        const num1 = parseFloat(document.getElementById('num1').value);
        const num2 = parseFloat(document.getElementById('num2').value);
        
        if (isNaN(num1) || isNaN(num2)) {
            this.showError('请输入有效的数字');
            return;
        }

        let result;
        let operationText;

        switch(operation) {
            case 'add':
                result = this.module._add(num1, num2);
                operationText = `${num1} + ${num2}`;
                break;
            case 'subtract':
                result = this.module._subtract(num1, num2);
                operationText = `${num1} - ${num2}`;
                break;
            case 'multiply':
                result = this.module._multiply(num1, num2);
                operationText = `${num1} × ${num2}`;
                break;
            case 'divide':
                if (num2 === 0) {
                    this.showError('除数不能为零');
                    return;
                }
                result = this.module._divide(num1, num2);
                operationText = `${num1} ÷ ${num2}`;
                break;
            case 'power':
                result = this.module._power(num1, num2);
                operationText = `${num1} ^ ${num2}`;
                break;
        }

        this.displayResult(result, operationText, `${num1} ${this.getOperationSymbol(operation)} ${num2}`);
    }

    performSquareRoot() {
        const num1 = parseFloat(document.getElementById('num1').value);
        
        if (isNaN(num1)) {
            this.showError('请输入有效的数字');
            return;
        }

        if (num1 < 0) {
            this.showError('不能对负数开平方根');
            return;
        }

        const result = this.module._squareRoot(num1);
        const operationText = `√${num1}`;

        this.displayResult(result, operationText, `√${num1}`);
    }

    getOperationSymbol(operation) {
        const symbols = {
            'add': '+',
            'subtract': '-',
            'multiply': '×',
            'divide': '÷',
            'power': '^'
        };
        return symbols[operation];
    }

    displayResult(result, operationText, displayText) {
        const resultDiv = document.getElementById('result');
        const resultValue = document.getElementById('resultValue');
        const operationInfo = document.getElementById('operationInfo');

        resultValue.textContent = result;
        operationInfo.textContent = `${displayText} = ${result}`;
        
        resultDiv.classList.remove('hidden');
        resultDiv.classList.add('result-animation');

        // 添加到历史记录
        this.addToHistory(operationText, result);
        
        // 移除动画类以便下次使用
        setTimeout(() => {
            resultDiv.classList.remove('result-animation');
        }, 500);
    }

    addToHistory(operation, result) {
        const historyItem = {
            id: Date.now(),
            operation,
            result,
            timestamp: new Date().toLocaleString()
        };

        this.history.unshift(historyItem);
        
        // 只保留最近10条记录
        if (this.history.length > 10) {
            this.history = this.history.slice(0, 10);
        }

        localStorage.setItem('calcHistory', JSON.stringify(this.history));
        this.updateHistoryDisplay();
    }

    updateHistoryDisplay() {
        const historyList = document.getElementById('historyList');
        
        if (this.history.length === 0) {
            historyList.innerHTML = '<p class="text-gray-500 text-sm">暂无计算历史</p>';
            return;
        }

        historyList.innerHTML = this.history.map(item => `
            <div class="history-item">
                <div class="flex justify-between items-start">
                    <span class="font-medium">${item.operation}</span>
                    <span class="text-green-600 font-semibold">${item.result}</span>
                </div>
                <div class="text-xs text-gray-500 mt-1">${item.timestamp}</div>
            </div>
        `).join('');
    }

    showError(message) {
        alert(`错误: ${message}`);
    }
}

// 页面加载完成后初始化计算器
document.addEventListener('DOMContentLoaded', () => {
    window.calculator = new WasmCalculator();
});

// 全局函数供按钮调用
function performOperation(operation) {
    window.calculator.performOperation(operation);
}

function performSquareRoot() {
    window.calculator.performSquareRoot();
}
